package leecode;

/**
 * @author dushougudu
 */
public class IntersectionNode {

    public static void main(String[] args) {
        ListNode c5 = new ListNode(5, null);
        ListNode c4 = new ListNode(4, c5);
        ListNode c8 = new ListNode(8, c4);
        ListNode a1 = new ListNode(1, c8);
        ListNode a4 = new ListNode(4, a1);
        ListNode b1 = new ListNode(1, c8);
        ListNode b0 = new ListNode(0, b1);
        ListNode b5 = new ListNode(5, b0);

        System.out.println(getIntersectionNode(a4, b5));
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x, ListNode n) {
            val = x;
            next = n;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }

    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }

        ListNode a = headA;
        ListNode b = headB;

        while (a != b) {

            if (a != null) {
                a = a.next;
            } else {
                a = headB;
            }

            if (b != null) {
                b = b.next;
            } else {
                b = headA;
            }

        }

        return a;


    }
}
